import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserInfo } from "@/store/user.js";
const userInfoState = useUserInfo();

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10 * 1000
})

service.interceptors.request.use(
    config => {
        if (userInfoState.authorization) {
            config.headers['authorization'] = userInfoState.authorization
        }

        return config
    },

    error => {
        console.log('err ' + error)
        ElMessage.error('err ' + error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        var code = response.data.code
        if (code === 406 ) {
            localStorage.clear()
        }

        if (code !== 200) {
            ElMessage.error(response.data.msg)
            return Promise.reject(response);
        }

        return Promise.resolve(response.data.data);
    },
    error => {
        ElMessage.error('err ' + error)
        let { message } = error
        if (message == 'Network Error') {
            message = "后端接口异常"
        } else if (message.includes("timeout")) {
            message = "请求超时"
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常"
        }
        return Promise.reject(message)
    }
)

export default service